package com.lyq;

import org.json.JSONArray;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class jsonFileWrite {
    JSONArray jsonArray;
    String filename;
    public jsonFileWrite(JSONArray jsonArray, String filename){
        this.jsonArray=jsonArray;
        this.filename=filename;
    }
    public String FileWrite(){
        String adrees=null;
        try {
            jsonFileWrite.Tool tool=new jsonFileWrite.Tool();
            File file=new File(filename);
             adrees=file.getCanonicalPath();
            System.out.println("写入到"+adrees);
            file.createNewFile();
            Writer writer= new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
            writer.write(tool.stringToJSON(String.valueOf(jsonArray)));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("写入失败请检查文件名字");
            return null;
        }
        System.out.println("写入成功，结束程序");
        return adrees;
    }
    private class Tool {
        private boolean isTab = true;
        public String stringToJSON(String strJson) {
            int tabNum = 0;
            StringBuffer jsonFormat = new StringBuffer();
            int length = strJson.length();
            for (int i = 0; i < length; i++) {
                char c = strJson.charAt(i);
                if (c == '{') {
                    tabNum++;
                    jsonFormat.append(c + "\n");
                    jsonFormat.append(getSpaceOrTab(tabNum));
                } else if (c == '}') {
                    tabNum--;
                    jsonFormat.append("\n");
                    jsonFormat.append(getSpaceOrTab(tabNum));
                    jsonFormat.append(c);
                } else if (c == ',') {
                    jsonFormat.append(c + "\n");
                    jsonFormat.append(getSpaceOrTab(tabNum));
                } else {
                    jsonFormat.append(c);
                }
            }
            return jsonFormat.toString();
        }
        public String getSpaceOrTab(int tabNum) {
            StringBuffer sbTab = new StringBuffer();
            for (int i = 0; i < tabNum; i++) {
                if (isTab) {
                    sbTab.append('\t');
                } else {
                    sbTab.append("    ");
                }
            }
            return sbTab.toString();
        }
    }
}
